package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//实现用户信息的增删改查
public class UserDao {
    public User getUserByUserId(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 sql 语句
            String sql = "select * from user where userId = " + userId;
            statement = connection.prepareStatement(sql);
            // 3. 执行 sql 语句
            resultSet = statement.executeQuery();
            // 4. 查询结果
            if (resultSet.next()){
                User user = new User();
                user.setUserID(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //5. 释放资源
            DBUtil.close(connection, statement, resultSet);
        }

        return null;
    }
    public User getUserByUserName(String username){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 sql 语句
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            // 3. 执行 sql 语句
            resultSet = statement.executeQuery();
            // 4. 查询结果
            if (resultSet.next()){
                User user = new User();
                user.setUserID(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //5. 释放资源
            DBUtil.close(connection, statement, resultSet);
        }

        return null;
    }
}
